package com.byq.mm.gateway;

import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.View;
import android.view.WindowManager;
import android.widget.GridView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import com.byq.mm.gateway.adapter.HomeAdapter;
import com.byq.mm.gateway.adapter.ManageAction;
import com.byq.mm.smartlib.service.SmartConnectionService;
import com.byq.mm.smartlib.component.SmartGestureListener;
import com.tc.gateway.ProxyException;
import com.tc.gateway.device.GeneralDevice;
import com.tc.gateway.device.ha.DimmableLight;
import com.tc.gateway.device.ha.OnoffLight;
import com.tc.gateway.device.ha.PressureSensor;
import com.tc.gateway.device.ha.TemperatureSensor;
import com.tc.gateway.event.RefreshEvent;


public class HomeActivity extends Activity{
	AssistanceApplication application;
	View deviceContainer;
	View sceneContainer;
	View manageContainer;
	GridView deviceGrid;
	GridView sceneGrid;
	GridView manageGrid;
	GestureDetector gesture;
	private ViewFlipper flipper;
	HomeAdapter adapter;
	BroadcastReceiver messageReceiver;

	void updateAll() {
		updateGrid(deviceGrid);
		updateGrid(sceneGrid);
		updateGrid(manageGrid);
	}

	void updateGrid(GridView v) {
		HomeAdapter ad = (HomeAdapter) v.getAdapter();
		ad.reset();

	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		application = (AssistanceApplication) getApplication();
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.home);

		flipper = (ViewFlipper) findViewById(R.id.homeFlipper);
		gesture = new GestureDetector(new SmartGestureListener(flipper));


		deviceContainer = findViewById(R.id.deviceContainer);
		sceneContainer = findViewById(R.id.sceneContainer);
		manageContainer = findViewById(R.id.manageContainer);

		deviceGrid = (GridView) findViewById(R.id.deviceGrid);
		sceneGrid = (GridView) findViewById(R.id.sceneGrid);
		manageGrid = (GridView) findViewById(R.id.manageGrid);
		manageGrid.setAdapter(new ManageAdapter(application, this));

		deviceGrid.setAdapter(new DeviceAdapter(application, this));
		sceneGrid.setAdapter(new SceneAdapter(application, this));

		messageReceiver = new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				if (intent.getAction().equals(RefreshEvent.class.getName())) {
					updateAll();
				}
				if (intent.getAction().equals(
						AssistanceAction.ACTION_DEVICE_CONFIG_UPDATE)) {
					updateGrid(deviceGrid);
				}
				if (intent.getAction().equals(
						AssistanceAction.ACTION_HOME_ERROR)) {
					Toast
							.makeText(HomeActivity.this, "jjj",
									Toast.LENGTH_SHORT).show();
					updateAll();
					refresh.setTitle("����");
				}

			}

		};

		IntentFilter mf = new IntentFilter();
		mf.addAction(RefreshEvent.class.getName());
		mf.addAction(AssistanceAction.ACTION_HOME_ERROR);
		mf.addAction(AssistanceAction.ACTION_DEVICE_CONFIG_UPDATE);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
			registerReceiver(messageReceiver, mf,RECEIVER_NOT_EXPORTED);
		}

		deviceGrid.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				gesture.onTouchEvent(event);
				return false;
			}
		});
		sceneGrid.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				gesture.onTouchEvent(event);
				return false;
			}
		});
		manageGrid.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				gesture.onTouchEvent(event);
				return false;
			}
		});

		Intent aimConServ = new Intent(this, SmartConnectionService.class);
		startService(aimConServ);
	}

	MenuItem login;
	MenuItem register;
	MenuItem workConfig;

	MenuItem wallpaper;
	MenuItem sipsetting;
	MenuItem refresh;

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		boolean result = super.onCreateOptionsMenu(menu);
		SubMenu set = menu.addSubMenu("����");
		sipsetting = set.add("ͨ������");
		login = set.add("�˺�����");
		workConfig = set.add("��������");

		wallpaper = menu.add("��ֽ");

		register = menu.add("�豸ע��");
		if (application.getHomeApplication() == null
				|| !application.getHomeApplication().isStarted())
			refresh = menu.add("����");
		else
			refresh = menu.add("ˢ��");

		return result;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		if (register == item) {

			handler.sendEmptyMessage(0);
		}
		if (refresh == item) {
			if (!application.getHomeApplication().isStarted())
				try {
					application.getHomeApplication().start();
				} catch (ProxyException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			else
				application.getHomeApplication().getGatewayEngine().refresh();
			if (application.getHomeApplication() == null
					|| !application.getHomeApplication().isStarted())
				refresh.setTitle("����");
			else
				refresh.setTitle("ˢ��");
			// this.mGrid.invalidate();
		}
		// rtsp://rmv8.bbc.net.uk/news/olmedia/n5ctrl/summaries/entertain/nb_liquid_news.rm

		return true;

	}

	// private String defination(GeneralDevice d) {
	//
	// XmlSerializer serializer = Xml.newSerializer();
	// StringWriter writer = new StringWriter();
	// try {
	// serializer.setOutput(writer);
	// serializer.startDocument("UTF-8", true);
	// ProtocolStreamer.streamDevice(serializer, d);
	// serializer.endDocument();
	// return writer.toString();
	// } catch (Exception e) {
	// throw new RuntimeException(e);
	// }
	// }
	Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

		}

	};

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		boolean b = super.dispatchTouchEvent(ev);
		if (!b)
			gesture.onTouchEvent(ev);
		return b;

	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (messageReceiver == null)
			return;
		this.unregisterReceiver(messageReceiver);
		this.messageReceiver = null;
	}

}

class DeviceAdapter extends HomeAdapter {
	public DeviceAdapter(AssistanceApplication es, Activity c) {
		super(es, c);
		// TODO Auto-generated constructor stub
	}

	protected boolean action(final int position) {

		GeneralDevice e = (GeneralDevice) DeviceAdapter.this.getItem(position);

		if (e instanceof OnoffLight) {
			e.action();
		}
		if (e instanceof PressureSensor) {
			Intent intent = new Intent();

			intent.putExtra("id", e.getId());
			intent.setClass(ctx, PressureSensorActivity.class);
			ctx.startActivity(intent);
			ctx.overridePendingTransition(R.anim.zoom_enter, R.anim.hold);
		}
		if (e instanceof TemperatureSensor) {
			Intent intent = new Intent();
			intent.putExtra("id", e.getId());
			intent.setClass(ctx, TemperatureSensorActivity.class);
			ctx.startActivity(intent);
			ctx.overridePendingTransition(R.anim.zoom_enter, R.anim.hold);
		}
		if (e instanceof DimmableLight) {
			Intent intent = new Intent();
			intent.putExtra("id", e.getId());
			intent.setClass(ctx, DimmableLightActivity.class);
			ctx.startActivity(intent);
			ctx.overridePendingTransition(R.anim.zoom_enter, R.anim.hold);
		}

		return false;
	}

	@Override
	protected void fetch() {
		AndroidHomeApplication ha = application.getHomeApplication();
		devices = new ArrayList(ha.getGatewayEngine().getDeviceManager().getDevices());
	}
}

class ManageAdapter extends HomeAdapter {
	public ManageAdapter(AssistanceApplication es, Activity c) {
		super(es, c);
		// TODO Auto-generated constructor stub
	}

	protected boolean action(final int position) {
		Object o = ManageAdapter.this.getItem(position);

		ManageAction ma = (ManageAction) o;
		if (ma.id.equals(ManageAction.GROUP)) {
			Intent intent = new Intent();

			intent.setClass(ctx, GroupManageActivity.class);
			ctx.startActivity(intent);
			ctx.overridePendingTransition(R.anim.zoom_enter, R.anim.hold);
		}
		if (ma.id.equals(ManageAction.DEVICE)) {
			Intent intent = new Intent();

			intent.setClass(ctx, DeviceManageActivity.class);
			ctx.startActivity(intent);
			ctx.overridePendingTransition(R.anim.zoom_enter, R.anim.hold);
		}
		return false;
	}

	@Override
	protected void fetch() {

		devices = ManageAction.manageActions;
	}
}

class SceneAdapter extends HomeAdapter {
	public SceneAdapter(AssistanceApplication es, Activity c) {
		super(es, c);
		// TODO Auto-generated constructor stub
	}

	protected boolean action(final int position) {
		Object o = SceneAdapter.this.getItem(position);

		return false;
	}

	@Override
	protected void fetch() {
		AndroidHomeApplication ha = application.getHomeApplication();
		devices = new LinkedList(ha.getGatewayEngine().getSceneManager()
				.getAll());
	}
}